import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common";
import { Button, message, Popover, Badge, Spin, Icon, Modal } from 'antd'
import AdvancedTable from 'components/advanced-table'
import Info from 'components/info'
import autoAuditService from "../auto-audit.service";
import SlideFrame from 'components/slide-frame'
import AutoAuditRuleSlide from '../auto-audit-rule-slide'
import EditAuditDetail from "../edit-audit-detail";
import menuRoute from "routes/menuRoute";

const { SimpleTable } = AdvancedTable;

class AutoAuditRuleDetail extends Component {

  tableRef = null;

  //渲染规则参数类型
  getRuleType = value => {
    const { mappingTable } = this.state;
    let result = '';
    mappingTable.autoAuditRelative.map(item => {
      item.value === `${value}` && (result = item.text);
    });
    return result;
  };

  //渲染规则参数
  getRuleParameter = value => {
    const { mappingTable } = this.state;
    let result = '';
    mappingTable.autoAuditType.map(item => {
      item.value === `${value}` && (result = item.text);
    });
    return result;
  };

  //渲染取值方式
  getCompareType = value => {
    switch (value) {
      case 'contain':
        return messages('expense-14.key440')/*包含*/;
      case 'exclude':
        return messages('expense-14.key441')/*排除*/;
      default:
        return '-'
    }
  };

  //渲染取值
  getItemValue = (value, record) => {
    switch (record.paramValueType) {
      case 1002:
        return <Popover
          content={`${value.showValue[0].showValue}-${value.showValue[1].showValue}`}
          placement="topLeft"
        >
          <span>{value.showValue[0].showValue}-{value.showValue[1].showValue}</span>
        </Popover>;
      default:
        let showString = '';
        let length = value.showValue.length;
        value.showValue.map((item,index) => {
          index === length - 1 ? (showString += item.showValue) : (showString += `${item.showValue},`);
        });
        return <Popover content={showString} placement="topLeft">
          <span>{showString}</span>
        </Popover>;
    }
  };

  columns = [{
    title: messages('expense-14.key426')/*规则参数类型*/, dataIndex: 'ruleType',
    render: this.getRuleType
  }, {
    title: messages('expense-14.key427')/*规则参数*/, dataIndex: 'ruleParameter',
    render: this.getRuleParameter
  }, {
    title: messages('expense-14.key428')/*取值方式*/, dataIndex: 'compareType',
    render: this.getCompareType
  }, {
    title: messages('expense-14.key429')/*取值*/, dataIndex: 'itemValue',
    render: this.getItemValue
  }, {
    title: messages('common.column.status')/*状态*/, dataIndex: 'enabled',
    render: value => value ?
      <Badge text={messages('expense-14.key363')/*启用temp*/} status='success'/> :
      <Badge text={messages('expense-14.key311')/*禁用temp*/} status='error'/>
  }];

  service = (page, size) => {
    const { ruleId } = this.props.params;
    return autoAuditService.getRuleDetailTable({
      page,
      size,
      ruleId
    })
  };

  state = {
    mapLoading: true,
    mappingTable: {},
    headLoading: false,
    head: {},
    slideShow: false,
    title: '',
    ruleDetailInfo: null
  };

  componentDidMount() {
    this.getMapping();
    this.getHead();
  }

  getMapping = () => {
    autoAuditService.mapDetail().then(res => {
      this.setState({ mappingTable: res.data, mapLoading: false });
    }).catch(() => {
      message.error(messages('expense-14.key430')/*出错了，请联系管理员*/);
    });
  };

  getHead = () => {
    const { ruleId } = this.props.params;
    this.setState({ headLoading: true });
    autoAuditService.getRuleInfo(ruleId)
      .then(res => {
        this.setState({ head: res.data });
      })
      .finally(() => {
        this.setState({ headLoading: false });
      })
  };

  afterCloseSlideFrame = flag => {
    flag && this.getHead();
  };

  handleEditHead = () => {
    const { head } = this.state;
    SlideFrame.open({
      title: '编辑规则',
      content: AutoAuditRuleSlide,
      afterClose: this.afterCloseSlideFrame,
      params: {
        record: head,
        noCompany: true
      }
    }, this);
  };

  handleRowClick = record => {
    this.setState({
      ruleDetailInfo:record,
      title: messages('expense-14.key397')/*编辑规则*/
    },() => {
      this.setState({ slideShow:true });
    });
  };

  handleNew = () => {
    this.setState({
      title: messages('expense-14.key413')/*新建规则*/,
      ruleDetailInfo: null
    },() => {
      this.setState({ slideShow: true });
    })
  };

  handleMore = () => {
    Modal.info({
      title: messages('expense-14.key432')/*帮助*/,
      content: <div>
        <div className='help-header-title'><span>{messages('expense-14.key433')/*规则校验逻辑*/}</span></div>
        <div style={{margin: '5px 0px'}}>{messages('expense-14.key434')/*（1）同一条规则详情内的取值间为或；*/}</div>
        <div style={{margin: '5px 0px'}}>{messages('expense-14.key435')/*（2）不同的规则详情间取交；*/}</div>
      </div>,
      width: 600
    });
  };

  goBack = () => {
    this.context.router.push(menuRoute.getRouteItem('auto-audit').url);
  };

  attributes = [{
    title: '规则编码',
    dataIndex: 'ruleCode'
  }, {
    title: '规则名称',
    dataIndex: 'ruleName'
  }, {
    title: '所属账套',
    dataIndex: 'setOfBooksName'
  }, {
    title: '优先级',
    dataIndex: 'priority'
  }, {
    title: '状态',
    dataIndex: 'enabled',
    render: enabled => enabled ?
      <Badge text={messages('expense-14.key363')/*启用temp*/} status='success'/> :
      <Badge text={messages('expense-14.key311')/*禁用temp*/} status='error'/>
  }];

  render() {
    const { mapLoading, head, headLoading, slideShow, ruleDetailInfo, title } = this.state;
    const { ruleId } = this.props.params;
    return (
      <div className="auto-audit-rule-detail full-height-page">
        {mapLoading ? <Spin /> : <SimpleTable
          onRef={ref => this.tableRef = ref}
          columns={this.columns}
          service={this.service}
          rowKey='id'
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          footer={<div>
            <Button onClick={this.goBack}>返回</Button>
          </div>}
        >
          <div style={{ marginTop: 20 }}>
            <Info
              title='基本信息'
              attributes={this.attributes}
              dataSource={head}
              loading={headLoading}
            >
              <a style={{ marginRight: 20 }} onClick={this.handleMore}>
                <Icon type="bulb" />&nbsp;了解更多
              </a>
              <Button type='primary' onClick={this.handleEditHead}>编辑</Button>
            </Info>
            <div className='advanced-table-buttons'>
              <Button type='primary' onClick={this.handleNew}>新建</Button>
            </div>
          </div>
        </SimpleTable>}
        <SlideFrame
          show={slideShow}
          title={title}
          hasFooter
          hasMask
          params={{
            ruleDetailInfo,
            ruleId,
            slideShow
          }}
          content={EditAuditDetail}
          onClose={this.toState({ slideShow: false })}
          afterClose={isRefresh => {
            this.setState({ slideShow: false });
            isRefresh === true && this.tableRef.getList();
          }}/>
      </div>
    )
  }

  static contextTypes = {
    router: PropTypes.object
  }

}

function mapStateToProps(state){
  return {
    tenantInfo: state.login.tenant,
  }
}

export default connect(mapStateToProps)(AutoAuditRuleDetail);
